package com.msr.controller;

import com.msr.bean.Food;
import com.msr.bean.FoodType;
import com.msr.service.FoodService;
import com.msr.service.FoodTypeService;
import com.msr.utils.PageUtils;
import com.msr.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tom
 * @version V1.0
 * @Package com.msr.controller
 * @date 2024/1/12 9:54
 * @Copyright © 株式会社多言语系统研究所
 */
@Controller
@RequestMapping("/food")
public class FoodController {
    @Autowired
    private FoodService foodService;
    @Autowired
    private FoodTypeService foodTypeService;

    /**
     * 不分页查询
     * @param food
     * @param model
     * @return
     */
    @RequestMapping("/foodAll")
    public String foodAll(Food food, Model model){
        List<Food> foods = foodService.foodAll(food);
        model.addAttribute("foods",foods);
        return "foodList";
    }

    /**
     * 分页查询
     * @param model
     * @param pageNo  当前页码
     * @param pageSize 每页大小
     * @return
     */
    @RequestMapping("/foodAllPage/{pageNo}/{pageSize}")
    public String foodAllPage(HttpSession session, Model model, Food food, @PathVariable("pageNo") Integer pageNo, @PathVariable("pageSize") Integer pageSize){
        //说明：文本框中是有内容的
        if(food.getTitle()!=null){
            //在session中保存文本框中的内容
            session.setAttribute("title",food.getTitle());
        }

        //获取菜系的列表数据
        List<FoodType> foodTypes = foodTypeService.getFoodTypes(null);
        session.setAttribute("foodTypes",foodTypes);

        Map<String,Object> map = new HashMap<>();
        map.put("title",session.getAttribute("title"));
        map.put("pageStart",(pageNo-1)*pageSize);  //开始下标索引=（当前页码-1） * 每页大小
        map.put("pageSize",pageSize);

        //分页查询数据
        List<Food> foods = foodService.foodAllPage(map);

        //修改food中的title内容，是由session中获取的
        Object objTitle = session.getAttribute("title");
        if(objTitle!=null){
            food.setTitle(objTitle.toString());
        }

        //创建分页工具类
        int totalSile = foodService.totalSize(food);
        PageUtils<Food> pageUtils = new PageUtils<Food>(pageSize,pageNo,totalSile,foods);
        model.addAttribute("pageUtils",pageUtils);//保存分页工具类

        return "foodList";
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping("/toSaveFoodPage")
    public String toSaveFoodPage(HttpSession session){
        return "saveFood";
    }

    /**
     * 处理添加业务
     * @param model
     * @return
     */
    @RequestMapping("/addFood")
    public void addFood(Model model, Food food, @RequestParam("imageUrl") MultipartFile file, HttpServletResponse response) throws IOException {
        //处理乱码
        response.setContentType("text/html;charset=utf-8");

        String imgName = UploadUtils.upload(file,response,"/public/upload");

        //给菜品的图片属性赋值
        food.setPhoto(imgName);

        //调用service业务
        int num = foodService.addFood(food);
        if(num>0){
            response.getWriter().write("<script>alert('菜品添加成功！');location.href='/food/foodAllPage/1/5';</script>");
        }else{
            response.getWriter().write("<script>alert('菜品添加失败！');</script>");
        }
    }

    /**
     * 根据id查找菜品
     * @param model
     * @throws IOException
     */
    @RequestMapping("/findFoodById/{foodId}/{type}")
    public String findFoodById(Model model,@PathVariable("foodId") Integer foodId,@PathVariable("type") String type) throws IOException {
        //调用service业务
        Food food = foodService.findFoodById(foodId);
        model.addAttribute("food",food);
        if(type.equals("a")){
            //更新回显
            return "updateFood";
        }else{
            //菜品详细
            return "caixiangxi";
        }
    }

    /**
     * 修改菜品
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("/updateFood")
    public void updateFood(Model model,Food food,HttpServletResponse response,@RequestParam("imageUrl") MultipartFile file) throws IOException {
        //处理乱码
        response.setContentType("text/html;charset=utf-8");
        //图片上传
        String imgName = UploadUtils.upload(file,response,"/public/upload");
        //给菜品的图片属性赋值
        food.setPhoto(imgName);

        //调用service业务
        int num = foodService.updateFood(food);
        if(num>0){
            response.getWriter().write("<script>alert('菜品修改成功！');location.href='/food/foodAllPage/1/5';</script>");
        }else{
            response.getWriter().write("<script>alert('菜品修改失败！');</script>");
        }
    }

    /**
     * 删除菜品
     * @param response
     * @throws IOException
     */
    @RequestMapping("/delFood/{id}")
    public void delFood(HttpServletResponse response,@PathVariable("id") Integer id) throws IOException {
        //处理乱码
        response.setContentType("text/html;charset=utf-8");
        //调用service业务
        int num = foodService.delFood(id);
        if(num>0){
            response.getWriter().write("<script>alert('菜品删除成功！');location.href='/food/foodAllPage/1/5';</script>");
        }else{
            response.getWriter().write("<script>alert('菜品删除失败！');</script>");
        }
    }
}
